package com.ccn.ui.a1ui;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.PointFEvaluator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.view.animation.OvershootInterpolator;

import androidx.annotation.Nullable;

import com.ccn.ui.R;

/**
 * 仿QQ气泡效果
 */
public class A1_2_5DragBubbleView extends View {

    //气泡默认状态 静止
    private final int BUBBLE_STATE_DEFAULT = 0;
    //气泡连接
    private final int BUBBLE_STATE_CONNECT = 1;
    //气泡分离
    private final int BUBBLE_STATE_APART = 2;
    //气泡消失
    private final int BUBBLE_STATE_DISMISS = 3;
    //气泡半径
    private float mBubbleRadius = 12;
    //气泡颜色
    private int mBubbleColor;
    //气泡消息文字
    private String mTextStr;
    //气泡消息文字颜色
    private int mTextColor;
    //气泡文字大小
    private float mTextSize = 12;
    //不动气泡的半径
    private float mBubFixedRadius;
    //可动气泡的半径
    private float mBubMovableRadius;
    //不动气泡的圆心
    private PointF mBubFixedCenter;
    //可动气泡的圆心
    private PointF mBubMovableCenter;
    //气泡的画笔
    private Paint mBubblePaint;
    //文字的画笔
    private Paint mTextPaint;
    //文本绘制区域
    private Rect mTextRect;
    //贝塞尔曲线path
    private Path mBezierPath;
    //爆炸效果的画笔
    private Paint mBurstPaint;
    //爆炸绘制区域
    private Rect mBurstRect;
    //气泡状态标志
    private int mBubbleState = BUBBLE_STATE_DEFAULT;
    //两气泡圆心距离
    private float mDist;
    //气泡连接状态最大圆心距离
    private float mMaxDist;
    //手指触摸偏移量
    private final float MOVE_OFFSET;
    //气泡爆炸的bitmap数组
    private Bitmap[] mBurstBitmapArray;
    //是否在执行气泡爆炸动画
    private boolean mIsBurstAnimStart = false;
    //当前气泡爆炸图片index
    private int mCurDrawableIndex;
    //气泡爆炸的图片id数组
    private int[] mBurstDrawableArray = {R.mipmap.burst1, R.mipmap.burst2, R.mipmap.burst3};

    private boolean canReset = false;
    public A1_2_5DragBubbleView(Context context) {
        this(context, null);
    }

    public A1_2_5DragBubbleView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public A1_2_5DragBubbleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray array = context.obtainStyledAttributes(attrs,
                R.styleable.A1_2_5DragBubbleView, defStyleAttr, 0);
        mBubbleRadius = array.getDimension(R.styleable.A1_2_5DragBubbleView_bubble_radius,
                mBubbleRadius);
        mBubbleColor = array.getColor(R.styleable.A1_2_5DragBubbleView_bubble_color, Color.RED);
        mTextStr = array.getString(R.styleable.A1_2_5DragBubbleView_bubble_text);
        mTextSize = array.getDimension(R.styleable.A1_2_5DragBubbleView_bubble_textSize, mTextSize);
        mTextColor = array.getColor(R.styleable.A1_2_5DragBubbleView_bubble_textColor, Color.WHITE);
        array.recycle();

        //两个圆半径大小一致
        mBubFixedRadius = mBubbleRadius;
        mBubMovableRadius = mBubFixedRadius;
        mMaxDist = 8 * mBubbleRadius;

        MOVE_OFFSET = mMaxDist / 4;

        //抗锯齿
        mBubblePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mBubblePaint.setColor(mBubbleColor);
        mBubblePaint.setStyle(Paint.Style.FILL);

        mBezierPath = new Path();

        //文本画笔
        mTextPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mTextPaint.setColor(mTextColor);
        mTextPaint.setTextSize(mTextSize);
        mTextRect = new Rect();

        //爆炸画笔
        mBurstPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mBurstPaint.setFilterBitmap(true);
        mBurstRect = new Rect();
        mBurstBitmapArray = new Bitmap[mBurstDrawableArray.length];
        for (int i = 0; i < mBurstDrawableArray.length; i++) {
            //将气泡爆炸的drawable转为bitmap
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), mBurstDrawableArray[i]);
            mBurstBitmapArray[i] = bitmap;
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        initBubbleCenter(w, h);
    }

    private void initBubbleCenter(int w, int h) {
        //不动气泡圆心
        if (mBubFixedCenter == null) {
            mBubFixedCenter = new PointF(w / 2, h / 2);
        } else {
            mBubFixedCenter.set(w / 2, h / 2);
        }

        //可动气泡圆心
        if (mBubMovableCenter == null) {
            mBubMovableCenter = new PointF(w / 2, h / 2);
        } else {
            mBubMovableCenter.set(w / 2, h / 2);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //只有当绘制结束以后才允许重置
        canReset = true;

        if (mBubbleState != BUBBLE_STATE_DISMISS) {
            //绘制气泡加消息数量
            canvas.drawCircle(mBubMovableCenter.x, mBubMovableCenter.y, mBubMovableRadius, mBubblePaint);
            mTextPaint.getTextBounds(mTextStr, 0, mTextStr.length(), mTextRect);
            canvas.drawText(mTextStr,
                    mBubMovableCenter.x - mTextRect.width() / 2,
                    mBubMovableCenter.y + mTextRect.height() / 2,
                    mTextPaint);
        }

        if (mBubbleState == BUBBLE_STATE_CONNECT) {
            //绘制不动气泡
            canvas.drawCircle(mBubFixedCenter.x, mBubFixedCenter.y, mBubFixedRadius, mBubblePaint);
            //绘制贝赛尔曲线 详见图片bezeir 求出a b c d g的坐标
            //贝塞尔曲线控制点坐标
            int iAnchorX = (int) ((mBubFixedCenter.x + mBubMovableCenter.x) / 2);
            int iAnchorY = (int) ((mBubFixedCenter.y + mBubMovableCenter.y) / 2);

            float sinTheta = (mBubMovableCenter.y - mBubFixedCenter.y) / mDist;
            float cosTheta = (mBubMovableCenter.x - mBubFixedCenter.x) / mDist;

            //b坐标
            float iBubMovableStartX = mBubMovableCenter.x + sinTheta * mBubMovableRadius;
            float iBubMovableStartY = mBubMovableCenter.y - cosTheta * mBubMovableRadius;

            //a坐标
            float iBubFixedEndX = mBubFixedCenter.x + mBubFixedRadius * sinTheta;
            float iBubFixedEndY = mBubFixedCenter.y - mBubFixedRadius * cosTheta;

            //d坐标
            float iBubFixedStartX = mBubFixedCenter.x - mBubFixedRadius * sinTheta;
            float iBubFixedStartY = mBubFixedCenter.y + mBubFixedRadius * cosTheta;
            //c坐标
            float iBubMovableEndX = mBubMovableCenter.x - sinTheta * mBubMovableRadius;
            float iBubMovableEndY = mBubMovableCenter.y + cosTheta * mBubMovableRadius;

            mBezierPath.reset();
            //d->c
            mBezierPath.moveTo(iBubFixedStartX, iBubFixedStartY);
            mBezierPath.quadTo(iAnchorX, iAnchorY, iBubMovableEndX, iBubMovableEndY);

            //移动到B点 b->a
            mBezierPath.lineTo(iBubMovableStartX, iBubMovableStartY);
            mBezierPath.quadTo(iAnchorX, iAnchorY, iBubFixedEndX, iBubFixedEndY);
            mBezierPath.close();

            canvas.drawPath(mBezierPath, mBubblePaint);
        }

        if (mBubbleState == BUBBLE_STATE_DISMISS
                && mCurDrawableIndex < mBurstBitmapArray.length) {
            mBurstRect.set(
                    (int) (mBubMovableCenter.x - mBubMovableRadius),
                    (int) (mBubMovableCenter.y - mBubMovableRadius),
                    (int) (mBubMovableCenter.x + mBubMovableRadius),
                    (int) (mBubMovableCenter.y + mBubMovableRadius)
            );
            canvas.drawBitmap(mBurstBitmapArray[mCurDrawableIndex], null, mBurstRect, mBurstPaint);
        }
        //1.静止状态，一个气泡加消息数量

        //2.连接状态，一个气泡+消息熟练+贝赛尔曲线，本身位置上的气泡，大球位置可变化

        //3.分离状态，一个气泡加消息数量

        //4.消失状态，爆炸效果
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (mBubbleState != BUBBLE_STATE_DISMISS) {
                    mDist = (float) Math.hypot(event.getX() - mBubFixedCenter.x,
                            event.getY() - mBubFixedCenter.y);
                    if (mDist < mBubbleRadius + MOVE_OFFSET) {//加上MOVE_OFFSET是为了方便拖拽
                        mBubbleState = BUBBLE_STATE_CONNECT;
                    } else {
                        mBubbleState = BUBBLE_STATE_DEFAULT;
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if (mBubbleState != BUBBLE_STATE_DEFAULT) {
                    mDist = (float) Math.hypot(event.getX() - mBubFixedCenter.x,
                            event.getY() - mBubFixedCenter.y);
                    mBubMovableCenter.x = event.getX();
                    mBubMovableCenter.y = event.getY();
                    if (mBubbleState == BUBBLE_STATE_CONNECT) {
                        if (mDist < mMaxDist - MOVE_OFFSET) {
                            //当拖拽的距离在指定范围内，那么调整不动气泡的半径
                            mBubFixedRadius = mBubbleRadius - mDist / 8;
                        } else {
                            //当拖拽的距离超过指定范围，那么改成分离状态
                            mBubbleState = BUBBLE_STATE_APART;
                        }
                    }
                    invalidate();
                }
                break;
            case MotionEvent.ACTION_UP:
                if (mBubbleState == BUBBLE_STATE_CONNECT) {
                    //橡皮筋动画效果
                    startBubbleRestAnim();
                } else if (mBubbleState == BUBBLE_STATE_APART) {
                    if (mDist < 2 * mBubbleRadius) {
                        startBubbleRestAnim();
                    } else {
                        //分离状态  爆炸效果
                        startBubbleBurstAnim();
                    }

                }
                break;
        }
        return true;
    }

    /**
     * 爆炸效果
     */
    private void startBubbleBurstAnim() {
        mBubbleState = BUBBLE_STATE_DISMISS;
        ValueAnimator anim = ValueAnimator.ofInt(0, mBurstBitmapArray.length);
        anim.setDuration(500);
        anim.setInterpolator(new LinearInterpolator());
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mCurDrawableIndex = (int) animation.getAnimatedValue();
                invalidate();
            }
        });
        anim.start();
    }

    /**
     * 橡皮筋动画效果
     */
    private void startBubbleRestAnim() {
        ValueAnimator anim = ValueAnimator.ofObject(
                new PointFEvaluator(),
                new PointF(mBubMovableCenter.x, mBubMovableCenter.y),
                new PointF(mBubFixedCenter.x, mBubFixedCenter.y));
        anim.setDuration(200);
        anim.setInterpolator(new OvershootInterpolator(5f));
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                mBubMovableCenter = (PointF) animation.getAnimatedValue();
                invalidate();
            }
        });
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                mBubbleState = BUBBLE_STATE_DEFAULT;
            }
        });
        anim.start();
    }

    public void reset() {
        //只有当绘制结束以后才允许重置
        if (canReset) {
            mBubbleState = BUBBLE_STATE_DEFAULT;
            initBubbleCenter(getWidth(), getHeight());
            invalidate();
        }

    }
}
